package com.opticon.vaadinR.core.log;

import com.google.common.base.Joiner;
import com.vaadin.ui.TextArea;
import org.apache.log4j.Logger;
import org.apache.log4j.WriterAppender;
import org.apache.log4j.spi.LoggingEvent;

import java.util.LinkedList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * This class is a
 */
public class TextAreaAppender extends WriterAppender {
    private static Logger logger = Logger.getLogger(TextAreaAppender.class);

    static private TextArea iTextArea = null;
    static private ExecutorService iService = Executors.newSingleThreadExecutor();
    static private LinkedList iQueue = new LinkedList();
    static private int iMaxQueueSize = 1000;

    public TextAreaAppender() {
        logger.debug("initializing TextAreaAppender");
    }

    /**
     * Set the target JTextArea for the logging information to appear.
     */
    static public void setTextArea(TextArea aTextArea) {
        TextAreaAppender.iTextArea = aTextArea;
        System.out.println("setting textarea");
    }

    /**
     * Format and then append the loggingEvent to the stored
     * JTextArea.
     */
    public void append(LoggingEvent loggingEvent) {
        final String message = this.layout.format(loggingEvent);
        if(iQueue.size() > iMaxQueueSize){
            iQueue.removeLast();
        }
        iQueue.addFirst(message);

        iService.submit(new Runnable() {
            public void run() {
                String lContent = Joiner.on("").join(iQueue);
                iTextArea.setValue(lContent);
                iTextArea.requestRepaint();
            }
        });
    }
}
